/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle.commandhandles.customcommands;

import de.altitude.cimuelle.Config;
import de.altitude.cimuelle.MessageBundle;
import de.altitude.cimuelle.SendMail;
import de.altitude.cimuelle.coop.CoopGame;
import de.altitude.cimuelle.db.DatabaseCoopData;
import de.altitude.cimuelle.db.DatabaseManager;
import de.altitude.cimuelle.db.DatabasePlayerInfo;
import de.altitude.cimuelle.utils.ServerOperations;
import de.altitude.cimuelle.utils.StringUtils;
import de.altitudecustomcommands.Player;
import de.altitudecustomcommands.playerHandler;
import de.altitudecustomcommands.serverInformations;
import org.apache.log4j.Logger;

import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Class description:
 * processes the coop Commands from custom_json
 * User: cybernaut
 * Date: 08.10.11
 * Time: 16:44
 */
public class CommandCoopGame {
    private final static Logger LOGGER = Logger.getLogger("CommandCoopGame");
    @SuppressWarnings({"FieldCanBeLocal"})
    private final serverInformations server;
    @SuppressWarnings({"FieldCanBeLocal"})
    private final playerHandler playerList;

    public CommandCoopGame(serverInformations server, playerHandler playerList) {
        this.server = server;
        this.playerList = playerList;
    }

    public void showGame(String port, Player player, int coopId) {
        LOGGER.info(port + ":Got showGameRequest with id " + coopId);
        CoopGame coopGame = DatabaseCoopData.getCoopGameById(coopId);
        if (coopGame != null) {
            ServerOperations.sendServerWhisper(port, player.getName(), coopGame.showGameData());
        } else {
            ServerOperations.sendServerWhisper(port, player.getName(), MessageBundle.getString("wcoopGameNotFound", "ID", String.valueOf(coopId)));
        }
    }

    public void coopTopTenMap(String port, Player player, String map) {
        List<CoopGame> coopMaps = DatabaseCoopData.getCoopGameRanksByPortMap(port, map);
        StringBuilder sb = new StringBuilder();
        sb.append(CoopGame.getShortInfoHeader()).append("\n");
        for (CoopGame coopGame : coopMaps) {
            sb.append(coopGame.getShortInfo());
            sb.append("\n");
        }
        ServerOperations.sendServerWhisper(port, player.getName(), sb.toString());
    }

    public void coopTopTenPlayer(String port, Player player) {
        List<DatabasePlayerInfo> players = DatabaseManager.getInstance().getRankBy(port, 10, DatabaseManager.COOP_POINTS_COL);
        sendRank(port, player, players);
    }

    private void sendRank(String port, Player player, List<DatabasePlayerInfo> players) {
        StringBuilder sb = new StringBuilder();
        StringUtils.buildRankString(Config.getInstance(), port, players, sb, DatabaseManager.COOP_POINTS_COL);
        ServerOperations.sendServerWhisper(port, player.getName(), sb.toString());
    }


    public void coopGetRank(String port, Player player) {
        List<DatabasePlayerInfo> players = DatabaseManager.getInstance().getRankByVapor(player, DatabaseManager.COOP_POINTS_COL);
        sendRank(port, player, players);
    }

    public void coopGetPRank(String port, Player player, Player cplayer) {
        List<DatabasePlayerInfo> players = DatabaseManager.getInstance().getRankByVapor(cplayer, DatabaseManager.COOP_POINTS_COL);
        sendRank(port, player, players);
    }

    public void adminManageGame(String port, String action, int coopId, Player player) {
        // Delete game from statistics including player points if possible
        CoopGame coopGame = DatabaseCoopData.getCoopGameById(coopId);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("ID", String.valueOf(coopId));
        map.put("ACTION", action);

        if (coopGame != null) {
            coopGame.removePointsFromPlayers();
            coopGame.delete();
            ServerOperations.sendServerWhisper(port, player.getName(), MessageBundle.getString("coopAdminManageGame_success", map));
        } else {
            ServerOperations.sendServerWhisper(port, player.getName(), MessageBundle.getString("coopAdminManageGame_notfound", map));
        }
    }

    public void adminManagePoints(String port, Player player, String action, String tableColumn, int points, String playerArg) {
        HashMap<String, String> map = new HashMap<String, String>();
        String message = "";

        DatabasePlayerInfo target = DatabaseManager.getInstance().getPlayerStats(port, playerArg);
        if (target == null) {
            ArrayList<DatabasePlayerInfo> players = DatabaseManager.getInstance().getPlayerFromDatabaseByName(port, playerArg);
            if (players.size() > 1) {
                message = MessageBundle.getString("coopAdminManagePoints_nameNotClear", map);
                ServerOperations.sendServerWhisper(port, player.getName(), message);
            } else {
                target = players.get(0);
            }
        }
        if (target != null) {
            int pointsToAdd = 0;
            if ("increase".equals(action)) {
                pointsToAdd = points;
            } else if ("decrease".equals(action)) {
                pointsToAdd = 0 - points;
            }

            if ("kills".equals(tableColumn)) {
                if ("reset".equals(action)) {
                    target.setKills(0);
                } else {
                    target.setKills(target.getKills() + pointsToAdd);
                }
            } else if ("deaths".equals(tableColumn)) {
                if ("reset".equals(action)) {
                    target.setDeaths(0);
                } else {
                    target.setDeaths(target.getDeaths() + pointsToAdd);
                }
            } else if ("goals".equals(tableColumn)) {
                if ("reset".equals(action)) {
                    target.setGoals(0);
                } else {
                    target.setGoals(target.getGoals() + pointsToAdd);
                }
            } else if ("coop".equals(tableColumn)) {
                if ("reset".equals(action)) {
                    target.setCoopPoints(0);
                } else {
                    target.setCoopPoints(target.getCoopPoints() + pointsToAdd);
                }
            }
            if (target.saveToDB()) {
                message = MessageBundle.getString("coopAdminManagePoints_success", map);
            } else {
                message = MessageBundle.getString("coopAdminManagePoints_no_success", map);
            }

        } else {
            message = MessageBundle.getString("coopAdminManagePoints_playerNotFound", map);
        }
        ServerOperations.sendServerWhisper(port, player.getName(), message);
    }

    public void reportBug(Config config, String port, Player player, String bugMessage) {
        try {
            String receiver = config.getConfigByPort(port, "reportBugReceiver", "");
            if (!receiver.isEmpty()) {
                SendMail.postMail(config.getConfigByPort(port, "reportBugReceiver", ""), "Report Bug from Altitude Coop ", bugMessage, config.getConfigByPort(port, "reportBugSender", ""));
                ServerOperations.sendServerWhisper(port, player.getName(), MessageBundle.getString("reportBugSend"));
                return;
            } else {
                LOGGER.error("No reportBug receiver found. Message could not be send.");
            }
        } catch (MessagingException e) {
            LOGGER.error(e, e);
        }
        ServerOperations.sendServerWhisper(port, player.getName(), MessageBundle.getString("reportBugError"));
    }
}
